﻿using System;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using NLog;

namespace BookSourceVerification.handlers;

class UrlHandler : IHandler<JObject>
{
    private readonly Logger _logger = LogManager.GetCurrentClassLogger();

    public bool IsChecked(JObject node, HandlerResult result)
    {
        if (result.Data is string) return true;
        _logger.Error("url为空");
        return false;
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="node"></param>
    /// <param name="result">上一个过滤器想要传递给下一个过滤器的数据，可以为空</param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public Task DoHandler(JObject node, HandlerResult result)
    {
        Uri uri;
        try
        {
            // 如果DoubtHandler先执行，data不可是空的
            var url = (string)result.Data!;
            uri = new Uri(url);
        }
        catch (Exception e)
        {
            _logger.Error(e);
            result.Fail();
            return Task.CompletedTask;
        }

        result.Success($"https://{uri.Host}");
        return Task.CompletedTask;
    }

    public void AfterHandler()
    {
    }
}